﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Interface;
using NetDon.OA.Interface.eLogistics;
using NetDon.Utilities;

namespace NetDon.OA.Portal.Finance
{
    [Navigation("干线流程", "营收台账编辑")]
    public partial class RevenueMachineAccountEdit : NavigationPageBase
    {

        public Guid Id
        {
            get { return Parameters.GetGuid("Id"); }

        }

        public bool ViewModel
        {
            get { return Parameters.GetBoolean("ViewModel", false); }
        }

        protected Guid RouteTypeId
        {
            set { ViewState["RouteTypeId"] = value; }
            get
            {
                if (ViewState["RouteTypeId"] != null)
                    return Guid.Parse(ViewState["RouteTypeId"].ToString());
                return Guid.Empty;
            }
        }

        protected string DeliveryProvince
        {
            set { ViewState["DeliveryProvince"] = value; }
            get
            {
                if (ViewState["DeliveryProvince"] != null)
                    return (ViewState["DeliveryProvince"].ToString());
                return string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.txtCarSharingCostWithFactory.Attributes.Add("onchange", "calculateRevenueAccount(this);");
            this.txtUnloadingCostWithFactory.Attributes.Add("onchange", "calculateRevenueAccount(this);");
            this.txtSubsidy.Attributes.Add("onchange", "calculateRevenueAccount(this);");
            this.txtOtherRevenue.Attributes.Add("onchange", "calculateRevenueAccount(this);");

            if (!IsPostBack)
            {
                CancelButton = btnCancel;
                LoadInitialData();
            }
        }

        private void LoadInitialData()
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            var revenueMachineAccount = service.GetRevenueMachineAccount(Id, false);
            FormPanelStore.DataSource = revenueMachineAccount;
            FormPanelStore.DataBind();

            var orderService = ServiceContainer.GetService<IIssuingOrderService>();
            var order = orderService.GetSimpleIssuingOrder(revenueMachineAccount.IssuingOrderId.Value);
            RouteTypeId = order.RouteTypeId;

            txtIsCalculatedByWeight.Value = WebConfig.IsCalculateByWeight(order.GoodsShippedTypeId).ToString().ToLower();
            if (order.GoodsUnloadingCost.HasValue)
                txtGoodsUnloadingCost.Text = order.GoodsUnloadingCost.Value.ToString("#,###.00");
            this.txtReceivingOrderDate.Text = order.ReceivingOrderDate.ToString("yyyy-MM-dd");
            txtAcutalShippingDate.Text = (order.ActualShippingDate ?? DateTime.Now).ToString("yyyy-MM-dd");

            GridViewOrderDelivery.DataSource =
                orderService.GetIssuingOrderDeliveryByOrderId(revenueMachineAccount.IssuingOrderId.Value);
            GridViewOrderDelivery.DataBind();

            this.lblTransporationPlanCode.Text = order.TransportationPlanCode;

            txtActualEntruckingBoxAmount.Text = (order.ActualEntruckingBoxAmount).ToString("#,###");
            txtUnitCost.Text = (order.UnitCost ?? 0).ToString("#,###.0000");

            if (order.OrderVolumn.HasValue)
                txtOrdeVolumn.Text = order.OrderVolumn.Value.ToString("#,###.000");
            if (order.OrderWeight.HasValue)
                txtOrderWeight.Text = order.OrderWeight.Value.ToString("#,###.000");
            if (order.OrderQuantity.HasValue)
                txtOrderQuantity.Text = order.OrderQuantity.Value.ToString("#,###.00");

            if (ViewModel && !IsManager())
            {
                this.txtCarSharingCostWithFactory.Enabled =
                    this.txtUnloadingCostWithFactory.Enabled =
                  this.txtSubsidy.Enabled = this.txtExceptions.Enabled = txtOtherRevenue.Enabled = false;
                this.btnSave.Visible = false;
            }
        }



        protected void gridIssuingOrderDelivery_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var data = e.Row.DataItem as IssuingOrderDeliveryData;


                var txtRevenueUnitCost = (TextBox)e.Row.FindControl("txtRevenueUnitCost");
                var txtGoodsUnloadingPriceRatio = (TextBox)e.Row.FindControl("txtGoodsUnloadingPriceRatio");
                var service = ServiceContainer.GetService<IIssuingOrderService>();

                var revenueUnitCost = service.GetRevenueUnitCost(CurrentApplicationContext.CompanyId, data.DeliveryCity, RouteTypeId);
                if (revenueUnitCost.HasValue && !data.RevenueUnitCost.HasValue)
                    txtRevenueUnitCost.Text = revenueUnitCost.ToString();


                if (ViewModel && !IsManager())
                {
                    txtRevenueUnitCost.Enabled = txtGoodsUnloadingPriceRatio.Enabled = false;
                }

                txtRevenueUnitCost.Attributes.Remove("onblur");
                txtRevenueUnitCost.Attributes.Add("onblur",
                                                    "calculateRevenueAccount();return false;");
                txtGoodsUnloadingPriceRatio.Attributes.Remove("onblur");
                txtGoodsUnloadingPriceRatio.Attributes.Add("onblur",
                                                    "caclualteUnloadingCostWithFactory();return false;");

            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var service = ServiceContainer.GetService<IRevenueMachineAccountService>();
            var revenueMachineAccountData = ExtractIssuingOrder(service.GetRevenueMachineAccount(Id, true));

            bool result = service.ModifyRevenueMachineAccount(revenueMachineAccountData);
            bool result1 =
                ServiceContainer.GetService<IIssuingOrderService>().ModifyIssuingOrderDeliveies(this.RouteTypeId, DeliveryProvince,
                    ExtractIssuingOrderDelivery());
            if (result && result1)
            {
                Success("保存成功！");
                this.CloseWindow(true);
            }
        }


        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            var issuingOrderDeliveries = ExtractIssuingOrderDelivery();

            Success("计算成功！");
            this.CloseWindow(true);

        }


        private IEnumerable<IssuingOrderDeliveryData> ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderDeliveries = new List<IssuingOrderDeliveryData>();
            foreach (GridViewRow detailRow in GridViewOrderDelivery.Rows)
            {
                var issuingOrderDeliveryId = GridViewOrderDelivery.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderDelivery =
                    ServiceContainer.GetService<IIssuingOrderService>().GetIssuingOrderDelivery(issuingOrderDeliveryId);

                if (issuingOrderDelivery != null)
                {

                    issuingOrderDelivery.RevenueUnitCost = (detailRow.FindControl("txtRevenueUnitCost") as TextBox).Text.ToDecimal();
                    issuingOrderDelivery.GoodsUnloadingPriceRatio = (detailRow.FindControl("txtGoodsUnloadingPriceRatio") as TextBox).Text.ToDecimal();


                    issuingOrderDelivery.LastUpdatedBy = CurrentApplicationContext.UserId;
                    issuingOrderDelivery.LastUpdatedDate = DateTime.Now;
                    tempIssuingOrderDeliveries.Add(issuingOrderDelivery);
                }

            }

            return tempIssuingOrderDeliveries;
        }

        private RevenueMachineAccountData ExtractIssuingOrder(RevenueMachineAccountData machineAccountData)
        {
            machineAccountData.CarSharingCostWithFactory = this.txtCarSharingCostWithFactory.Text.ToDecimal() ?? 0;
            machineAccountData.UnloadingCostWithFactory = this.txtUnloadingCostWithFactory.Text.ToDecimal() ?? 0;
            machineAccountData.Subsidy = this.txtSubsidy.Text.ToDecimal() ?? 0;
            machineAccountData.OtherRevenue = txtOtherRevenue.Text.ToDecimal() ?? 0;
            machineAccountData.Exceptions = StringUtilities.Trim(this.txtExceptions.Text);
            machineAccountData.LastUpdatedBy = CurrentApplicationContext.UserId;
            machineAccountData.LastUpdatedDate = DateTime.Now;

            return machineAccountData;
        }

    }
}